package com.example.floatingpopulation.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.example.floatingpopulation.controller.dto.UserLoginDTO;
import com.example.floatingpopulation.controller.dto.forgetPasswordDTO;
import com.example.floatingpopulation.controller.request.BaseRequest;
import com.example.floatingpopulation.controller.request.LoginRequest;
import com.example.floatingpopulation.controller.request.RegisterRequest;
import com.example.floatingpopulation.entity.Password;
import com.example.floatingpopulation.entity.Permissions;
import com.example.floatingpopulation.entity.User;
import com.example.floatingpopulation.exception.ServiceException;
import com.example.floatingpopulation.mapper.UserMapper;
import com.example.floatingpopulation.utils.TokenUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.gson.Gson;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.lang.reflect.Field;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class UserServiceImpl implements com.example.floatingpopulation.service.UserService {
    private static final String DEFAULT_PASS = "123456";
    private static final String PASS_SALT = "qiu";

    @Autowired
    UserMapper userMapper;
    @Override
    public List<User> list() {
        return userMapper.list();
    }

    @Override
    public PageInfo<User> page(BaseRequest baseRequest) {
        PageHelper.startPage(baseRequest.getPageNum(),baseRequest.getPageSize());
        List<User> users = userMapper.listByCondition(baseRequest);
        return new PageInfo<>(users);
    }

    @Override
    public void save(User user) {
        Date date = new Date();
        // 如果没设置密码就默认密码为"123456"
        if (StrUtil.isBlank(user.getPassword())){
            user.setPassword(DEFAULT_PASS);
        }
        // 设置md5加密 防止解密再加字符
        user.setPassword(SecureUtil.md5(user.getPassword() + PASS_SALT));
        // 用户登录的账号
        user.setUserId(DateUtil.format(date,"yyyyMMdd") + Math.abs(IdUtil.fastSimpleUUID().hashCode()));
        userMapper.save(user);
    }

    @Override
    public void update(User user) {
        user.setUpdateTime(new Date());
        userMapper.updateById(user);
    }

    @Override
    public void deleteById(Integer id) {
        userMapper.deleteById(id);
    }

//    @Override
//    public UserLoginDTO login(LoginRequest request) {
//        //密码解密
//        request.setPassword(securePass(request.getPassword()));
//        User user = userMapper.getByidCardAndPassword(request);
//        if (user == null){
//            throw new ServiceException("用户名或密码错误");
//        }
//        UserLoginDTO loginDTO = new UserLoginDTO();
//        BeanUtils.copyProperties(user,loginDTO);
//        //生成token
//        String token = TokenUtils.genToken(String.valueOf(user.getId()), user.getPassword());
//        loginDTO.setToken(token);
//        // 查询权限
//        Permissions permissions = userMapper.getPermissions(loginDTO.getIsAdmin());
//        ArrayList<String> list = new ArrayList<>();
//        if (permissions != null) {
//            if ("1".equals(permissions.getAdd())) {
//                list.add("add");
//            }
//            if ("1".equals(permissions.getDel())) {
//                list.add("del");
//            }
//            if ("1".equals(permissions.getSet())) {
//                list.add("set");
//            }
//            if ("1".equals(permissions.getGet())) {
//                list.add("get");
//            }
//        }
//
//        // 将权限列表转换为数组并赋值给 loginDTO
//        loginDTO.setPermissions(list.toArray(new String[0]));
//        return loginDTO;
//    }
@Override
public UserLoginDTO login(LoginRequest request) {
    // 密码解密
    request.setPassword(securePass(request.getPassword()));
    User user = userMapper.getByidCardAndPassword(request);
    if (user == null) {
        throw new ServiceException("用户名或密码错误");
    }
    UserLoginDTO loginDTO = new UserLoginDTO();
    BeanUtils.copyProperties(user, loginDTO);
    // 生成 token
    String token = TokenUtils.genToken(String.valueOf(user.getId()), user.getPassword());
    loginDTO.setToken(token);
    // 查询权限
    Permissions permissions = userMapper.getPermissions(loginDTO.getIsAdmin());
    if (permissions != null) {
        List<String> list = Arrays.stream(Permissions.class.getDeclaredFields())
                .filter(field -> {
                    try {
                        field.setAccessible(true);
                        return "1".equals(field.get(permissions));
                    } catch (IllegalAccessException e) {
                        return false;
                    }
                })
                .map(Field::getName)
                .collect(Collectors.toList());
        // 直接将权限列表赋值给 loginDTO
        loginDTO.setPermissions(list);
    }
    return loginDTO;
}

    @Override
    public User getById(Integer id) {
        return userMapper.getById(id);
    }

    @Override
    public void resetPassword(User user) {
        // 重置密码为"123456"
        user.setPassword(DEFAULT_PASS);
        // 设置md5加密 防止解密再加字符
        user.setPassword(SecureUtil.md5(user.getPassword() + PASS_SALT));
        userMapper.resetPassword(user);
    }

    @Override
    public void updatePassword(Password password) {
        // 设置md5加密 防止解密再加字符
        password.setPassword(SecureUtil.md5(password.getConfirmPassword() + PASS_SALT));
        userMapper.updatePassword(password);
    }

    @Override
    public Boolean register(RegisterRequest request) {
        Date date = new Date();
        request.setPassword(SecureUtil.md5(request.getPassword()  + PASS_SALT));
        request.setUserId(DateUtil.format(date,"yyyyMMdd") + Math.abs(IdUtil.fastSimpleUUID().hashCode()));
        return userMapper.register(request);
    }

    @Override
    public void resetPasswordForget(forgetPasswordDTO dto) {
        dto.setNewPassword(SecureUtil.md5(dto.getNewPassword() + PASS_SALT));
        userMapper.updatePasswordForget(dto);
    }

    //加密方法 设置md5加密 防止解密再加字符
    private String securePass(String password){
        return SecureUtil.md5(password + PASS_SALT);
    }
}
